package com.autodatabase.xml.model;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import com.autodatabase.xml.XMLUtil;

public class DatabaseFactoryXmlModel extends XMLUtil {
	public static DatabaseFactoryXmlModel getInstance() {
		if(factory == null) {
			factory = new DatabaseFactoryXmlModel();
			factory.read();
		}

		return factory;
	}

	public static DatabaseFactoryXmlModel reload() {
		factory = new DatabaseFactoryXmlModel();
		factory.read();
		return factory;
	}
	
	@Override
	protected void writeXML(Document document) {
		document.clearContent();
		Element dbFactory = document.addElement("DatabaseFactory");
		
		if(items != null) {
			for(FactoryItemXmlModel item : items.values()) {
				item.writeXML(dbFactory);
			}
		}
	}

	@Override
	protected void parseXML(Document document) {
		Element root = document.getRootElement();

		if(root != null) {
			if("DatabaseFactory".equals(root.getName())) {
				Element dbFactory = root;
				List<Element> list = dbFactory.elements("FactoryItem");
				
				for(Element e : list) {
					FactoryItemXmlModel itemModel = new FactoryItemXmlModel();
					itemModel.parseXML(e);
					this.addItem(itemModel.getKey(), itemModel);
				}
			}
		}
	}
	
	
	public Map<String, FactoryItemXmlModel> getItems() {
		return items;
	}

	public void setItems(Map<String, FactoryItemXmlModel> items) {
		this.items = items;
	}

	public void addItem(String key, FactoryItemXmlModel item) {
		this.items.put(key, item);
	}

	@Override
	public String getFilePath() {
		String path = DatabaseFactoryXmlModel.class.getResource("/").getPath();
		String folderPath = path + "/" + folder;
		File store = new File(folderPath);

		if(!store.exists()) {
			store.mkdir();
		}
		
		return path + "/" + folder + "/" + fileName;
	}

	private Map<String, FactoryItemXmlModel> items = new HashMap<String, FactoryItemXmlModel>();
	private static String fileName = "DatabaseFactory.xml";
	private static String folder = "factory";
	private static DatabaseFactoryXmlModel factory;
}
